#include "udpServer.hpp"
#include <memory>
#include <cstdio>
#include <unordered_map>

using namespace std;
using namespace Server;

void Usage(const string &proc)
{
    // cout << "\nUsage:\n\t" << proc << " local_ip local_port\n" << endl;
    cout << "\nUsage:\n\t" << proc << " local_port\n" << endl;
}


// 业务逻辑与通信逻辑解耦
void handlerMessage(int sockfd, string clientIp, uint16_t clientPort, string message)
{
    string sendMsg = message + " [server echo]";

    // 开始返回数据
    struct sockaddr_in client;
    bzero(&client, sizeof(client));

    client.sin_family = AF_INET;
    client.sin_port = htons(clientPort);
    client.sin_addr.s_addr = inet_addr(clientIp.c_str());

    sendto(sockfd, sendMsg.c_str(), sendMsg.size(), 0, (struct sockaddr*)&client, sizeof(client));
}


int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }

    uint16_t port = atoi(argv[1]);

    unique_ptr<udpServer> usvr(new udpServer(handlerMessage, port));

    usvr->initServer();
    usvr->start();

    return 0;
}